/**
 * Created by Administrator on 2017/2/23.
 */
// 全局变量，获得当前的year，month，date（day）
var date = new Date()
var year = date.getFullYear()
var month = date.getMonth()
var day = date.getDate()
var hour=date.getHours()
var minute=date.getMinutes()
var tempyear //当有前一个月,后一个月后,临时的当前年
var tempmonth //当有前一个月,后一个月后,临时的当前月
var months = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
var weekdays = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
var C_words=["年","月","日","今天是","第","个工作周",];



// 全局变量结束

// 默认函数调用，显示当前日期
function getCurrent() {
    var weekd = date.getDay();
    var showcurrent =year+"年 "+months[month]+day+"日"
    //计算work week
    var ww = getWorkWeek()
    // 显示当天的信息
    document.getElementById("currentTime").innerHTML = year + "年" + months[month]
    document.getElementById("currentInfo").innerHTML = "今天是" + showcurrent + "，"
        + weekdays[weekd] + "，第" + ww+"个工作周";
    drawCalendar(year, month)
    //当天的css改变
    var frame = document.getElementById('days');
    var childs = frame.childNodes
    var td = document.createElement('div')
    td.className = "today"
    for (var i = 0; i < childs.length; i++) {
        if (childs[i].innerHTML == day) {
            childs[i].appendChild(td)
        }
    }
    //work week
    drawWW(year, month)
    var yparent = document.getElementById('selyear');
    var mparent = document.getElementById('selmonth');
    drawselect(yparent,mparent);
    removeOldEvents();
    readStorage();
};
// 获取当前工作周
function getWorkWeek() {
    // 获取当前的工作周
    var d1 = new Date();
    var d2 = new Date();
    var firstDate = d1.setFullYear(year, 0, 1);
    d2.setTime(firstDate);
    x = d2.getDay();
    var firstWeekLeft = (6 - x) % 6
    if (firstWeekLeft == 0) {
        d2.setFullYear(year, 0, 1)
    } else {
        d2.setFullYear(year, 0, 1 + firstWeekLeft + 1)
    }
    var d = new Date();
    var ww = (1 + parseInt((d.getTime() - d2.getTime()) / 1000 / 60 / 60 / 24 / 7)) + "";
    if (ww.length < 2) {
        ww = "0" + ww;
    }
    return ww
};
// 描绘工作周区域
function drawWW(y, m) {
    /*
    描绘侧边work week
    y 输入year
    m 输入month
    */
    var d1 = new Date();
    var d2 = new Date();
    var firstDate = d1.setFullYear(y, 0, 1);
    d2.setTime(firstDate);
    x = d2.getDay();
    var firstWeekLeft = (6 - x) % 6
    if (firstWeekLeft == 0) {
        d2.setFullYear(y, 0, 1)
    } else {
        d2.setFullYear(y, 0, 1 + firstWeekLeft + 1)
    }
    // 第一天的ww
    var d = new Date();
    var firstOfMonth = d.setFullYear(y, m, 1)
    d.setTime(firstOfMonth)
    var d = new Date();
    d.setTime(firstOfMonth)
    var startww = (1 + parseInt((d.getTime() - d2.getTime()) / 1000 / 60 / 60 / 24 / 7));
    //获取最后一天的WW
    var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    //判断是否闰年
    var a = y % 4
    var b = y % 100
    if (a == 0 && b != 0) {
        monthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    }
    var lastOfMonth = d.setFullYear(y, m, monthDays[m])
    var de = new Date();
    de.setTime(lastOfMonth)
    var endww = (1 + parseInt((de.getTime() - d2.getTime()) / 1000 / 60 / 60 / 24 / 7));
    var wwarray = []
    for (var i = 0; i < (endww - startww) + 1; i++) {
        wwarray.push(startww + i)
    }
    var parent = document.getElementById('getWorkWeek')
    while (parent.hasChildNodes()) {
        parent.removeChild(parent.firstChild);
    }
    for (var j = 0; j < wwarray.length; j++) {
        wwarray[j] = "" + wwarray[j]
        if (wwarray[j].length < 2) {
            wwarray[j] = "0" + wwarray[j]
        }
        var div = document.createElement("div")
        var node = document.createTextNode(wwarray[j])
        div.appendChild(node)
        div.className = "wwdiv"
        parent.appendChild(div)
    }

};
// 描绘主日历区域
function drawCalendar(y, m) {
    /*
     描绘主日历区域
     y 输入year
     m 输入month
     */
    var d3 = new Date()
    d3.setFullYear(y, m, 1)
    var firstDayOfMonth = d3.getDay()
    var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    //判断是否闰年
    var a = y % 4
    var b = y % 100
    if (a == 0 && b != 0) {
        monthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    }


    var frame = document.getElementById('days')
    while (frame.hasChildNodes()) {
        frame.removeChild(frame.firstChild);
    }
    for (var i = 1; i < 39; i++) {
        if (i < firstDayOfMonth + 1) {
            var div = document.createElement("div")
            var node = document.createTextNode("")
            div.appendChild(node);
            div.className += "" + "daysdiv"
            frame.appendChild(div)
        } else {
            var div = document.createElement("div");
            var node = document.createTextNode(i - firstDayOfMonth)
            var over = i - firstDayOfMonth - 1
            if (over < monthDays[m]) {
                div.appendChild(node);
                div.addEventListener('click', focusDay);
                var hdays = [1, 7, 8, 14, 15, 21, 22, 28, 29, 35, 36]
                var p = hdays.indexOf(i)
                if (p >= 0) {
                    div.className = "holidays daysdiv"
                } else if (p == -1) {
                    div.className = "daysdiv"
                }
                frame.appendChild(div)
            } else break
        }
    }

};
// 上一个月
function previous() {
    // 往前一个月
    if (tempyear) {
        var y = tempyear
        var m = tempmonth
        if (m == 0) {
            drawCalendar(y - 1, 11)
            drawWW(y - 1, 11)
            document.getElementById('currentTime').innerHTML = (y - 1) + " " + months[11]
            tempyear -= 1
            tempmonth = 11
        } else {
            drawCalendar(y, m - 1)
            drawWW(y, m - 1)
            document.getElementById('currentTime').innerHTML = y + " " + months[m - 1]
            tempmonth -= 1
        }
    } else {
        var y = year
        var m = month
        if (m == 0) {
            drawCalendar(y - 1, 11)
            drawWW(y - 1, 11)
            document.getElementById('currentTime').innerHTML = (y - 1) + " " + months[11]
            tempyear = year - 1
            tempmonth = 11
        } else {
            drawCalendar(y, m - 1)
            drawWW(y, m - 1)
            document.getElementById('currentTime').innerHTML = y + " " + months[m - 1]
            tempmonth = month - 1
            tempyear = year
        }

    }
    readStorage();
};
// 下一个月
function next() {
    // 往后一个月
    if (tempyear) {
        var y = tempyear
        var m = tempmonth
        if (m == 11) {
            drawCalendar(y + 1, 0)
            drawWW(y + 1, 0)
            document.getElementById('currentTime').innerHTML = (y + 1) + " " + months[0]
            tempyear += 1
            tempmonth = 0
        } else {
            drawCalendar(y, m + 1)
            drawWW(y, m + 1)
            document.getElementById('currentTime').innerHTML = y + " " + months[m + 1]
            tempmonth += 1
        }
    } else {
        var y = year
        var m = month
        if (m == 11) {
            drawCalendar(y + 1, 0)
            drawWW(y + 1, 0)
            document.getElementById('currentTime').innerHTML = (y + 1) + " " + months[0]
            tempyear = year + 1
            tempmonth = 0
        } else {
            drawCalendar(y, m + 1)
            drawWW(y, m + 1)
            document.getElementById('currentTime').innerHTML = y + " " + months[m + 1]
            tempmonth = month + 1
            tempyear = year
        }

    }
    readStorage();
}
// 回到今天
function backToday() {

    getCurrent()
    // 清空临时的全局变量year,month
    tempyear = undefined
    tempmonth = undefined
}
// 描绘select选项区域
function drawselect(yparent,mparent,dparent,hparent,minparent,currentday,sethour) {
    // 描绘时间跳转控件
    var ys = [];
    var ms = [];
    var ds=[];
    var hs=[];
    var mins=[5,10,15,20,25,30,35,40,45,50,55]
    for (var i = 0; i < 100; i++) {
        ys.push(1950 + i)
    }
    for (var j = 0; j < 12; j++) {
        ms.push(1 + j)
    }
    for (var l = 0; l < 24; l++) {
        hs.push(1 + l)
    }
    // 去掉重复
    if (yparent){
        while (yparent.hasChildNodes()) {
            yparent.removeChild(yparent.firstChild);
        };
        for (var a = 0; a < ys.length; a++) {
            var op = document.createElement('option');
            var node = document.createTextNode(ys[a]);
            op.appendChild(node);
            yparent.appendChild(op);
        }
        if (tempyear!=null) {
            for (var k = 0; k < yparent.options.length; k++) {
                if (yparent.options[k].innerHTML == tempyear) {
                    yparent.options[k].selected = true;
                    break;
                }
            }
        } else {
            for (var k1 = 0; k1 < yparent.options.length; k1++) {
                if (yparent.options[k1].innerHTML == year) {
                    yparent.options[k1].selected = true;
                    break;
                }
            }
        }
    } else {
        return
    };

    if (mparent){
        while (mparent.hasChildNodes()) {
            mparent.removeChild(mparent.firstChild);
        };
        for (var b = 0; b < ms.length; b++) {
            var op = document.createElement('option');
            var node = document.createTextNode(ms[b]);
            op.appendChild(node);
            mparent.appendChild(op)
        };
        if (tempmonth!=null) {
            for (var v = 0; v < mparent.options.length; v++) {
                if (mparent.options[v].innerHTML == tempmonth + 1) {
                    mparent.options[v].selected = true;
                    break;
                }
            }
        } else {
            for (var v1 = 0; v1 < mparent.options.length; v1++) {
                if (mparent.options[v1].innerHTML == month + 1) {
                    mparent.options[v1].selected = true;
                    break;
                }
            }
        }
    } else return

    if (dparent){
        var m=mparent.value;
        var y=yparent.value;
        var e=y%4;
        var f=y%100;
        var monthdays=[];
        if (e==0&&f!=0){
            monthdays= [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        } else {
            monthdays=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        }
        for (var n = 0; n < monthdays[m-1]; n++) {
            ds.push(1 + n)
        }
        while (dparent.hasChildNodes()) {
            dparent.removeChild(dparent.firstChild);
        };
        for (var c = 0; c < ds.length; c++) {
            var op = document.createElement('option');
            var node = document.createTextNode(ds[c]);
            op.appendChild(node);
            dparent.appendChild(op)
        }
        if (currentday) {
            for (var t = 0; t < dparent.options.length; t++) {
                if (dparent.options[t].innerHTML == currentday) {
                    dparent.options[t].selected = true;
                    break;
                }
            }
        } else {
            for (var t1 = 0; t1 < dparent.options.length; t1++) {
                if (dparent.options[t1].innerHTML == day) {
                    dparent.options[t1].selected = true;
                    break;
                }
            }
        }

    }else return

    if (hparent){
        while (hparent.hasChildNodes()) {
            hparent.removeChild(hparent.firstChild);
        };
        for (var d = 0; d < hs.length; d++) {
            var op = document.createElement('option');
            var node = document.createTextNode(hs[d]);
            op.appendChild(node);
            hparent.appendChild(op)
        }
        if (sethour) {
            for (var u = 0; u < hparent.options.length; u++) {
                if (hparent.options[u].innerHTML == sethour) {
                    hparent.options[u].selected = true;
                    break;
                }
            }
        }else {
                for (var u = 0; u < hparent.options.length; u++) {
                    if (hparent.options[u].innerHTML == 8) {
                        hparent.options[u].selected = true;
                        break;
                    }
            }
        }
    } else return

    if (minparent){
        while (minparent.hasChildNodes()) {
            minparent.removeChild(minparent.firstChild);
        };
        var op = document.createElement('option');
        var node = document.createTextNode(00);
        op.appendChild(node);
        minparent.appendChild(op);
        minparent.options[0].selected=true;

        for (var p = 0; p < mins.length; p++) {
            var op = document.createElement('option');
            var node = document.createTextNode(mins[p]);
            op.appendChild(node);
            minparent.appendChild(op)
        }


    }
}
// 跳转到某年某月
function gotosomewhere() {
    // 在选择控件选择日期后触发跳转
    var yparent = document.getElementById('selyear');
    var mparent = document.getElementById('selmonth');
    var ty = yparent.value;
    var tm = mparent.value;
    drawCalendar(ty, tm - 1);
    drawWW(ty, tm - 1);
    document.getElementById('currentTime').innerHTML = ty + " " + months[tm - 1]
    // 讲当前月赋值到临时的全局变量year和month
    tempyear = parseInt(ty);
    tempmonth = parseInt(tm-1);
    readStorage();
}
// 点击日期后触发的函数
function focusDay() {
    var c=this.childNodes
    for (var v=0;v<c.length;v++){
        var cclass=c[v].className;
        if (cclass=="focused"){
            addcomment(this)
        }
    }
    readStorage()
    // 删去其余天的class
    var grandparent=document.getElementById('days')
    var parents=grandparent.childNodes;
    for (var k=0;k<parents.length;k++) {
        var childs = parents[k].childNodes
        for (var i = 0; i < childs.length; i++) {
            var childClass = childs[i].className
            if (childClass == "focused") {
                parents[k].removeChild(parents[k].childNodes[i])
            }
        }
    }
    //当前点击，添加class
    var op=document.createElement('div');
    op.className="focused"
    this.appendChild(op);
    //显示focus 当前天的信息
    var tyear,tmonth,tday;
    if (tempyear){
        tyear=tempyear
    } else {
        tyear=year
    }
    if (tempmonth){
        tmonth=tempmonth+1
    } else {
        tmonth=month+1
    }
    tday=this.innerHTML.toString();
    if (tday.length > 2) {
        var x = tday.indexOf("<")
        tday = tday.slice(0, x)
    }
    document.getElementById('events-details').innerHTML = ""
    document.getElementById('events-title').innerHTML = tyear + "年" + tmonth + "月" + tday + "日："
    // 显示当前天的事件函数
    showDetails(tyear,tmonth,tday)
}
// 在下方显示当前天的事件的的函数，传入的参数为year，month，day
function showDetails(y,m,d){
  y=y.toString();
  m=m.toString();
  d=d.toString();
  var DOMdetail=document.getElementById('events-details');
  var storage=localStorage;
  var storagedData=[];
  var text="";
  if (storage){
         for (var i=99999;i>(99999-storage.length+1);i--){
        var value= storage.getItem(i);
         value=JSON.parse(value);
         storagedData.push(value);

     };
      console.log(storagedData);
      for (var j=0;j<storagedData.length;j++){
        // 这里写的雨点太暴力简单了，臃肿
        var styear=storagedData[j].stTime[0];
        var stmonth=storagedData[j].stTime[1];
        var stday=storagedData[j].stTime[2];
        var sthour=storagedData[j].stTime[3];

        if (styear==y&&stmonth==m&&stday==d){
          var stminute=storagedData[j].stTime[4];
          var endyear=storagedData[j].endTime[0];
          var endmonth=storagedData[j].endTime[1];
          var endday=storagedData[j].endTime[2];
          var endhour=storagedData[j].endTime[3];
          var endminute=storagedData[j].endTime[4];
          var title=storagedData[j].title;
          var details=storagedData[j].detail;
          DOMdetail.innerHTML=DOMdetail.innerHTML+"事件标题："+title+"。<br>"+
          "   开始时间："+styear+"年"+stmonth+"月"+stday+"日，"+sthour+"时"+stminute+"分 <br>"+
          "   结束时间："+endyear+"年"+endmonth+"月"+endday+"日，"+endhour+"时"+endminute+"分 <br>"+
          "   事件内容："+details+"<br><br>";

        } else continue

      }

  };
}
//调出添加事件页面的函数，element是指代当前的DOM
function addcomment(element) {

    document.getElementById('add-events').style.visibility="visible"
    var yparent = document.getElementById('addyear');
    var mparent = document.getElementById('addmonth');
    var dparent = document.getElementById('addday');
    var hparent = document.getElementById('addhour');
    var minparent = document.getElementById('addminute');
    var currentday=element.innerHTML;
    if (currentday.length > 2) {
            var x = currentday.indexOf("<")
            currentday = currentday.slice(0, x)
        }
    drawselect(yparent,mparent,dparent,hparent,minparent,currentday);
    var endyear = document.getElementById('endyear');
    var endmonth = document.getElementById('endmonth');
    var endday= document.getElementById('endday');
    var endhour = document.getElementById('endhour');
    var endminute = document.getElementById('endminute');
    drawselect(endyear,endmonth,endday,endhour,endminute,currentday,17)

    var eventtitle=document.getElementById('event-title').value;
    var eventdetails=document.getElementById('event-details').value;
    eventtitle="";
    eventdetails="";

};
// 准备书写切换中英文的函数，如果没有时间就不管他
function changeLang() {
   // 切换中英文显示
};
// 保存事件的函数，保存在localStorage中，key从99999开始自减
function saveEvent() {
    // 传值函数，要求a,b是数组
    function _importvalue(a,b) {
        if (a instanceof Array){
            if (b instanceof Array) {
                for (var i = 0; i < a.length; i++) {
                    b[i]=document.getElementById(a[i]).value;
                }
            }
        }
    }

    var title=document.getElementById('event-title').value;
    var details=document.getElementById('event-details').value;
    if (title.length<1){
        alert("请输入事件标题")
        return
    };
    var stArray=['addyear','addmonth','addday','addhour','addminute'];
    var endArray=['endyear','endmonth','endday','endhour','endminute'];
    var stTime=[]
    var endTime=[]
    _importvalue(stArray,stTime);
    _importvalue(endArray,endTime);
    // 存储到localstorage

    var storage=localStorage;
    if (storage){
        var obj={
            stTime:stTime,
            endTime:endTime,
            title:title,
            detail:details
        }
        var sObj=JSON.stringify(obj);
        // 设置key值，默认是99999,自减
        var key=99999-(storage.length-1/*这里的1是localstorage中除了几个必要的数据*/)
        storage.setItem(key,sObj);
    }
    closeEvent();
    readStorage();

}
// 删除当前主日历区域显示了的事件，主要是避免重复显示
function removeOldEvents() {
    var grandparent=document.getElementById('days');
    var parents=grandparent.childNodes;
    //首先需要清除，避免重复显示
    for (var v=0;v<parents.length;v++){
        var select=parents[v].querySelectorAll('.events');
        if (select!=[]) {
            for (var p=0;p<select.length;p++){
                parents[v].removeChild(select[p])
            }
        }
    }
}
// 读取LocalStorage，并且调用了appendEvents函数将事件描绘在主日历区域
function readStorage() {
    //清除当前日历页面中的event显示，避免重复

    var storage=localStorage;
    var storagedData=[];
    if (storage){
        console.info("开始读取localStorage数据")
       for (var i=99999;i>(99999-storage.length+1);i--){
          var value= storage.getItem(i);
          var value=JSON.parse(value);
           storagedData.push(value);

       };
        console.log(storagedData)
        console.info("结束读取localStorage数据")
    };
    removeOldEvents();
    //将读取的数据一个一个提取，显现在页面中
    for (var p=0;p<storagedData.length;p++){
        var y=storagedData[p].stTime[0];
        var m=storagedData[p].stTime[1];
        var d=storagedData[p].stTime[2];
        var title=storagedData[p].title;

        appendEvents(y,m,d,title);
    }

}

// 该函数的作用是将读取的事件描绘在主日历区，是readStorage（）函数中调用的一个子函数
function appendEvents(year,month,day,title){
    // 这个函数的作用是在日历中显示事件

    // 首先检查event是否在当前月
    if (tempyear){
        if (tempyear==year&&tempmonth==month-1){
            //这里才开始写append的代码
            var grandparent=document.getElementById('days');
            var parents=grandparent.childNodes;
            for (var i=0;i<parents.length;i++) {
                var textnode = parents[i].innerHTML;
                if (textnode) {
                    if (textnode.length > 2) {
                        var x = textnode.indexOf("<")
                        textnode = textnode.slice(0, x)
                    }
                    ;
                    if (textnode == day) {
                        //开始创建新的element
                        var creat = document.createElement('div');
                        var op = document.createTextNode(title);
                        creat.appendChild(op);
                        creat.className = "events"
                        parents[i].appendChild(creat)
                    }
                } else continue
            }
        }
    } else {
        var grandparent=document.getElementById('days');
        var parents=grandparent.childNodes;
        //首先需要清除，避免重复显示
        // 已在readStorage函数中调用局部函数清除

        for (var i=0;i<parents.length;i++){
            var textnode=parents[i].innerHTML;
            if (textnode){
                if (textnode.length > 2) {
                    var x = textnode.indexOf("<")
                    textnode = textnode.slice(0, x)
                };
                if(textnode==day){
                    //开始创建新的element
                    var creat=document.createElement('div');
                    var op=document.createTextNode(title);
                    creat.appendChild(op);
                    creat.className="events"
                    parents[i].appendChild(creat)
                }
            } else continue

        }
    }
}
// 关闭添加事件页面的函数
function closeEvent() {
    document.getElementById('add-events').style.visibility = "hidden";
}
